package com.leyou.search.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.common.vo.PageResult;
import com.leyou.item.pojo.*;
import com.leyou.search.client.BrandClient;
import com.leyou.search.client.CategoryClient;
import com.leyou.search.client.GoodsClient;
import com.leyou.search.client.SpecificationClient;
import com.leyou.search.pojo.Goods;
import com.leyou.search.pojo.SearchRequest;
import com.leyou.search.pojo.SearchResult;
import com.leyou.search.repository.GoodsRepository;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.LongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangwei
 * @date 2018/12/27 14:33
 */
@Service
public class SearchService {

    public static final boolean NewVersion = false;

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private BrandClient brandClient;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private SpecificationClient specClient;

    @Autowired
    private GoodsRepository repository;

    @Autowired
    private ElasticsearchTemplate template;

    public Goods buildGoods(Spu spu) {
        Long spuId = spu.getId();
        //查询分类
        List<Category> categories = categoryClient.queryCategoryByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
        if (CollectionUtils.isEmpty(categories)) {
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        List<String> names = categories.stream().map(Category::getName).collect(Collectors.toList());
        //查询品牌
        Brand brand = brandClient.queryBrandById(spu.getBrandId());
        if (brand == null) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        //搜索字段
        String all = spu.getTitle() + StringUtils.join(names, " ") + brand.getName();

        //查询sku
        List<Sku> skuList = goodsClient.querySkuBySpuId(spuId);
        if (CollectionUtils.isEmpty(skuList)) {
            throw new LyException(ExceptionEnum.GOODS_SKU_NOT_FOUND);
        }
        //对sku进行处理
        List<Map<String, Object>> skus = new ArrayList<>();
        //价格集合
        List<Long> priceList = new ArrayList<>();
        for (Sku sku : skuList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", sku.getId());
            map.put("title", sku.getTitle());
            map.put("price", sku.getPrice());
            map.put("images", StringUtils.substringBefore(sku.getImages(), ","));
            skus.add(map);
            //处理价格
            priceList.add(sku.getPrice());
        }
        //查询可以搜索的规格参数
        List<SpecParam> params = specClient.queryParamList(null, spu.getCid3(), true);
        // [{"id":7,"cid":76,"groupId":3,"name":"操作系统","numeric":false,"unit":"","generic":true,"searching":true,"segments":""},{"id":8,"cid":76,"groupId":4,"name":"CPU品牌","numeric":false,"unit":"","generic":true,"searching":true,"segments":""},{"id":10,"cid":76,"groupId":4,"name":"CPU核数","numeric":false,"unit":"","generic":true,"searching":true,"segments":""},{"id":11,"cid":76,"groupId":4,"name":"CPU频率","numeric":true,"unit":"GHz","generic":true,"searching":true,"segments":"0-1.0,1.0-1.5,1.5-2.0,2.0-2.5,2.5-"},{"id":12,"cid":76,"groupId":5,"name":"内存","numeric":false,"unit":"","generic":false,"searching":true,"segments":""},{"id":13,"cid":76,"groupId":5,"name":"机身存储","numeric":false,"unit":"","generic":false,"searching":true,"segments":""},{"id":14,"cid":76,"groupId":11,"name":"主屏幕尺寸（英寸）","numeric":true,"unit":"英寸","generic":true,"searching":true,"segments":"0-4.0,4.0-5.0,5.0-5.5,5.5-6.0,6.0-"},{"id":16,"cid":76,"groupId":6,"name":"前置摄像头","numeric":true,"unit":"万","generic":true,"searching":true,"segments":"0-500,500-1000,1000-1500,1500-2000,2500-"},{"id":17,"cid":76,"groupId":6,"name":"后置摄像头","numeric":true,"unit":"万","generic":true,"searching":true,"segments":"0-500,500-1000,1000-1500,1500-2000,2500-"},{"id":18,"cid":76,"groupId":7,"name":"电池容量（mAh）","numeric":true,"unit":"mAh","generic":true,"searching":true,"segments":"0-2000,2000-3000,3000-4000,4000-"}]
        if (CollectionUtils.isEmpty(params)) {
            throw new LyException(ExceptionEnum.SPEC_PARAM_NOT_FOUND);
        }
        //查询商品详情
        SpuDetail spuDetail = goodsClient.querySpuDetailById(spuId);
        //获取通用规格参数,值是数字和字符串类型
        // {"1":"华为（HUAWEI）","2":"荣耀畅玩7X","3":2017,"5":165,"6":"以实物为准","7":"Android","8":"海思（Hisilicon）","9":"麒麟659","10":"八核","11":2.36,"14":5.93,"15":"2160*1080(FHD)","16":800,"17":2000,"18":3340}
        Map<Long, String> genericSpec = JsonUtils.toMap(spuDetail.getGenericSpec(), Long.class, String.class);
        //获取特有规格参数，值是数组类型
        // {"4":["铂光金","幻夜黑","魅焰红","极光蓝"],"12":["4GB"],"13":["32GB"]}
        Map<Long, List<String>> specialSpec = JsonUtils.nativeRead(spuDetail.getSpecialSpec(), new TypeReference<Map<Long, List<String>>>() {
        });

        //规格参数,key是规格参数的名字,值是规格参数的值
        Map<String, Object> specs = new HashMap<>();
        for (SpecParam param : params) {
            //规格名称
            String key = getKey(param);
            Object value = "";
            if (param.getGeneric()) {
                value = genericSpec.get(param.getId());
                //判断是否是数据类型
                if (param.getNumeric()) {
                    //处理成段
                    chooseSegment(value.toString(), param);
                }
            } else {
                value = specialSpec.get(param.getId());
            }
            //存入map
            specs.put(key, value);
        }

        //构建goods对象
        Goods goods = new Goods();
        goods.setBrandId(spu.getBrandId());
        goods.setCid1(spu.getCid1());
        goods.setCid2(spu.getCid2());
        goods.setCid3(spu.getCid3());
        goods.setCreateTime(spu.getCreateTime());
        goods.setId(spuId);

        //搜索字段,包含标题,分类品牌,规格等
        goods.setAll(all);

        //所以sku的价格集合
        goods.setPrice(priceList);

        //所有sku的集合的json格式
        goods.setSkus(JsonUtils.toString(skus));

        //所有的可搜索的规格参数
        goods.setSpecs(specs);


        goods.setSubTitle(spu.getSubTitle());
        return goods;
    }

    private String chooseSegment(String value, SpecParam p) {
        double val = NumberUtils.toDouble(value);
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = NumberUtils.toDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = NumberUtils.toDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    public PageResult<Goods> search(SearchRequest request) {
        int page = request.getPage() - 1;
        int size = request.getSize();
        //创建查询构建器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 结果过滤
        queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{"id", "subTitle", "skus"}, null));
        //分页
        queryBuilder.withPageable(PageRequest.of(page, size));
        //过滤
        QueryBuilder basicQuery = QueryBuilders.matchQuery("all", request.getKey());
        queryBuilder.withQuery(basicQuery);
        //聚合分类和品牌
        //聚合分类
        String categoryAggName = "category_agg";
        queryBuilder.addAggregation(AggregationBuilders.terms(categoryAggName).field("cid3"));
        //品牌聚合
        String brandAggName = "brand_agg";
        queryBuilder.addAggregation(AggregationBuilders.terms(brandAggName).field("brandId"));
        //查询
        NativeSearchQuery nativeSearchQuery = queryBuilder.build();
        AggregatedPage<Goods> result = template.queryForPage(nativeSearchQuery, Goods.class);
        //解析结果分页
        long total = result.getTotalElements();
        int totalPage = result.getTotalPages();
        // [{"id":131,"skus":"[{\"images\":\"http://image.leyou.com/images/11/6/1524297580539.jpg\",\"price\":158800,\"id\":15937340742,\"title\":\"华为（HUAWEI） 华为nova2手机 极光蓝 全网通4G+64G\"},{\"images\":\"http://image.leyou.com/images/5/10/1524297580951.jpg\",\"price\":159900,\"id\":15969469881,\"title\":\"华为（HUAWEI） 华为nova2手机 草木绿 全网通4G+64G\"},{\"images\":\"http://image.leyou.com/images/2/6/1524297581267.jpg\",\"price\":169900,\"id\":15969469882,\"title\":\"华为（HUAWEI） 华为nova2手机 玫瑰金 全网通4G+64G\"},{\"images\":\"http://image.leyou.com/images/11/15/1524297579753.jpg\",\"price\":142800,\"id\":24556226085,\"title\":\"华为（HUAWEI） 华为nova2手机 曜石黑 移动全网通4G+64G\"},{\"images\":\"http://image.leyou.com/images/0/10/1524297580231.jpg\",\"price\":144900,\"id\":24556226088,\"title\":\"华为（HUAWEI） 华为nova2手机 流光金 移动全网通4G+64G\"}]","subTitle":"【移动版支持全网与全网版不做混发、请放心购买】<a href=\"https://item.jd.com/26397633043.html\" target=\"_blank\">【新品现货nova3e】</a>"},{"id":110,"skus":"[{\"images\":\"http://image.leyou.com/images/1/3/1524297534082.jpg\",\"price\":346600,\"id\":11768718240,\"title\":\"华为（HUAWEI） 华为P10 手机 陶瓷白色 全网通(4G+128G)\"},{\"images\":\"http://image.leyou.com/images/13/1/1524297533269.jpg\",\"price\":226800,\"id\":11768718242,\"title\":\"华为（HUAWEI） 华为P10 手机 钻雕金色 全网通(4G+64G)\"},{\"images\":\"http://image.leyou.com/images/4/0/1524297533738.jpg\",\"price\":236600,\"id\":11768718243,\"title\":\"华为（HUAWEI） 华为P10 手机 草木绿色 全网通(4G+64G)\"},{\"images\":\"http://image.leyou.com/images/1/14/1524297532833.jpg\",\"price\":226800,\"id\":11768718246,\"title\":\"华为（HUAWEI） 华为P10 手机 钻雕蓝色 全网通(4G+64G)\"},{\"images\":\"http://image.leyou.com/images/2/8/1524297534506.jpg\",\"price\":346600,\"id\":11768718250,\"title\":\"华为（HUAWEI） 华为P10 手机 玫瑰金色 全网通(4G+128G)\"},{\"images\":\"http://image.leyou.com/images/0/6/1524297532315.jpg\",\"price\":245800,\"id\":11768718251,\"title\":\"华为（HUAWEI） 华为P10 手机 曜石黑色 全网通(4G+64G)\"}]","subTitle":"现货速发！送229元原装视窗保护套+壳膜扣套装！<a href=\"https://item.jd.com/26652078862.html\" target=\"_blank\">华为P20点这</a>"},{"id":94,"skus":"[{\"images\":\"http://image.leyou.com/images/3/8/1524297500704.jpg\",\"price\":428800,\"id\":26816294479,\"title\":\"华为（HUAWEI） 华为P20 手机 宝石蓝 高配（6G+128G）\"},{\"images\":\"http://image.leyou.com/images/3/6/1524297501507.jpg\",\"price\":378800,\"id\":26816294480,\"title\":\"华为（HUAWEI） 华为P20 手机 樱粉金 标配（6G+64G）\"},{\"images\":\"http://image.leyou.com/images/6/15/1524297501076.jpg\",\"price\":428800,\"id\":26816294483,\"title\":\"华为（HUAWEI） 华为P20 手机 香槟金 高配（6G+128G）\"},{\"images\":\"http://image.leyou.com/images/4/3/1524297500161.jpg\",\"price\":428800,\"id\":26816294485,\"title\":\"华为（HUAWEI） 华为P20 手机 亮黑色 高配（6G+128G）\"}]","subTitle":"大量现货 华为直供货源！自带原装耳机 华为<a href=\"https://item.jd.com/26881279035.html\" target=\"_blank\">P20pro</a> 现货抢购！"},{"id":93,"skus":"[{\"images\":\"http://image.leyou.com/images/8/1/1524297497591.jpg\",\"price\":378800,\"id\":13164693175,\"title\":\"华为（HUAWEI） 华为P10 Plus 手机 陶瓷白 全网通(6G+128G)\"},{\"images\":\"http://image.leyou.com/images/1/2/1524297495532.jpg\",\"price\":378800,\"id\":13164693176,\"title\":\"华为（HUAWEI） 华为P10 Plus 手机 曜石黑 全网通(6G+128G)\"},{\"images\":\"http://image.leyou.com/images/10/9/1524297498088.jpg\",\"price\":378800,\"id\":13164693177,\"title\":\"华为（HUAWEI） 华为P10 Plus 手机 草木绿 全网通(6G+128G)\"},{\"images\":\"http://image.leyou.com/images/8/2/1524297496947.jpg\",\"price\":378800,\"id\":13164693182,\"title\":\"华为（HUAWEI） 华为P10 Plus 手机 钻雕金 全网通(6G+128G)\"},{\"images\":\"http://image.leyou.com/images/3/2/1524297496502.jpg\",\"price\":378800,\"id\":13164693185,\"title\":\"华为（HUAWEI） 华为P10 Plus 手机 钻雕蓝 全网通(6G+128G)\"},{\"images\":\"http://image.leyou.com/images/14/7/1524297499049.jpg\",\"price\":276600,\"id\":13164693190,\"title\":\"华为（HUAWEI） 华为P10 Plus 手机 玫瑰金 全网通(6G+64G)\"},{\"images\":\"http://image.leyou.com/images/11/7/1524297496098.jpg\",\"price\":378800,\"id\":17347463834,\"title\":\"华为（HUAWEI） 华为P10 Plus 手机 亮黑 全网通(6G+128G)\"},{\"images\":\"http://image.leyou.com/images/0/6/1524297498501.jpg\",\"price\":458800,\"id\":25573151670,\"title\":\"华为（HUAWEI） 华为P10 Plus 手机 兰玉限量定制版 全网通(6G+256G)\"}]","subTitle":"64G版本仅需2766元，256G 黑、金、玉色现货速发！<a href=\"https://item.jd.com/26652299286.html\" target=\"_blank\">P20 Pro点这</a>"},{"id":75,"skus":"[{\"images\":\"http://image.leyou.com/images/15/1/1524297449539.jpg\",\"price\":199900,\"id\":21577634824,\"title\":\"华为（HUAWEI） 华为nova3e 手机 幻夜黑 移动全网通 4GB+64GB\"},{\"images\":\"http://image.leyou.com/images/5/10/1524297450601.jpg\",\"price\":259900,\"id\":26399238748,\"title\":\"华为（HUAWEI） 华为nova3e 手机 樱语粉 移动全网通 4GB+64GB\"},{\"images\":\"http://image.leyou.com/images/7/12/1524297450218.jpg\",\"price\":219900,\"id\":26643400038,\"title\":\"华为（HUAWEI） 华为nova3e 手机 克莱因蓝 全网通 4GB+128GB\"},{\"images\":\"http://image.leyou.com/images/4/0/1524297451007.jpg\",\"price\":269900,\"id\":26643400039,\"title\":\"华为（HUAWEI） 华为nova3e 手机 铂光金 全网通 4GB+128GB\"}]","subTitle":"【现货热销】前置2400万自然美妆！<a href=\"https://item.jd.com/25390983397.html\" target=\"_blank\">【华为新品P20】</a>"},{"id":69,"skus":"[{\"images\":\"http://image.leyou.com/images/1/6/1524297435318.jpg\",\"price\":548800,\"id\":26881279026,\"title\":\"华为（HUAWEI） 华为P20pro 手机 宝石蓝 6G+128G\"},{\"images\":\"http://image.leyou.com/images/14/7/1524297436613.jpg\",\"price\":658800,\"id\":26881279030,\"title\":\"华为（HUAWEI） 华为P20pro 手机 樱粉金 6G+256G\"},{\"images\":\"http://image.leyou.com/images/14/7/1524297436217.jpg\",\"price\":618800,\"id\":26881279032,\"title\":\"华为（HUAWEI） 华为P20pro 手机 极光色 6G+128G\"},{\"images\":\"http://image.leyou.com/images/12/13/1524297435830.jpg\",\"price\":548800,\"id\":26881279035,\"title\":\"华为（HUAWEI） 华为P20pro 手机 亮黑色 6G+128G\"}]","subTitle":"华为直供货源大量现货！【宝石蓝128G及极光色全系为预售请见详情】自带原装耳机 <a href=\"https://item.jd.com/26816294484.html\" target=\"_blank\">华为P20</a>"},{"id":23,"skus":"[{\"images\":\"http://image.leyou.com/images/1/2/1524297352598.jpg\",\"price\":129900,\"id\":4093555,\"title\":\"华为畅享7 Plus 3GB+32GB 灰色 移动联通电信4G手机 双卡双待\"},{\"images\":\"http://image.leyou.com/images/15/11/1524297351474.jpg\",\"price\":149900,\"id\":4093559,\"title\":\"华为畅享7 Plus 4GB+64GB 流光金 移动联通电信4G手机 双卡双待\"},{\"images\":\"http://image.leyou.com/images/14/7/1524297352221.jpg\",\"price\":149900,\"id\":4093561,\"title\":\"华为畅享7 Plus 4GB+64GB 粉色 移动联通电信4G手机 双卡双待\"},{\"images\":\"http://image.leyou.com/images/1/6/1524297351168.jpg\",\"price\":149900,\"id\":4483108,\"title\":\"华为畅享7 plus 4GB+64GB 黑色 移动联通电信4G手机 双卡双待\"},{\"images\":\"http://image.leyou.com/images/12/12/1524297352928.jpg\",\"price\":149900,\"id\":4736647,\"title\":\"华为畅享7 plus 4GB+64GB 极光蓝 移动联通电信4G手机 双卡双待\"},{\"images\":\"http://image.leyou.com/images/5/10/1524297350655.jpg\",\"price\":149900,\"id\":4884236,\"title\":\"华为畅享7 Plus 4GB+64GB 香槟金 移动联通电信4G手机 双卡双待\"},{\"images\":\"http://image.leyou.com/images/4/0/1524297351853.jpg\",\"price\":149900,\"id\":4884258,\"title\":\"华为畅享7 plus 4GB+64GB 蓝色 移动联通电信4G手机 双卡双待\"}]","subTitle":"【限量领券立减100元】成交价1399元！4000毫安续航大电池！<a href='http://item.jd.com/6001257.html?from_saf=1' target='_blank'>畅享7S成交价低至1399元！</a>"},{"id":15,"skus":"[{\"images\":\"http://image.leyou.com/images/0/4/1524297336405.jpg\",\"price\":89900,\"id\":3755813,\"title\":\"华为 畅享6S 粉色 移动联通电信4G手机 双卡双待\"},{\"images\":\"http://image.leyou.com/images/14/5/1524297335567.jpg\",\"price\":89900,\"id\":4207732,\"title\":\"华为 畅享6S 金色 移动联通电信4G手机 双卡双待\"},{\"images\":\"http://image.leyou.com/images/4/15/1524297336063.jpg\",\"price\":89900,\"id\":4207778,\"title\":\"华为 畅享6S 银色 移动联通电信4G手机 双卡双待\"}]","subTitle":"骁龙芯片！金属机身！享看又享玩！<a  target=\"_blank\"  href=\"https://sale.jd.com/act/DhKrOjXnFcGL.html\">华为新品全面上线，更多优惠猛戳》》</a>"},{"id":8,"skus":"[{\"images\":\"http://image.leyou.com/images/6/11/1524297324064.jpg\",\"price\":69900,\"id\":3888216,\"title\":\"华为 畅享6 金色 移动联通电信4G手机 双卡双待\"},{\"images\":\"http://image.leyou.com/images/14/7/1524297324600.jpg\",\"price\":69900,\"id\":5305784,\"title\":\"华为 畅享6 白色 移动4G+版 移动联通电信4G手机 双卡双待\"}]","subTitle":"轻薄有型，电力十足！5英寸AMOLED屏幕，4100mAh大容量电池！<a  target=\"_blank\"  href=\"https://sale.jd.com/act/DhKrOjXnFcGL.html\">华为新品全面上线，更多优惠猛戳》》</a>"},{"id":7,"skus":"[{\"images\":\"http://image.leyou.com/images/13/7/1524297323037.jpg\",\"price\":119900,\"id\":3234246,\"title\":\"华为 G9 Plus 32GB 月光银 移动联通4G手机 双卡双待\"},{\"images\":\"http://image.leyou.com/images/4/4/1524297322527.jpg\",\"price\":119900,\"id\":3604173,\"title\":\"华为 G9 Plus 32GB 铂雅金 移动联通电信4G手机 双卡双待\"}]","subTitle":"高清大屏，长续航，骁龙芯片，表里不凡！<a href='https://sale.jd.com/act/DhKrOjXnFcGL.html' target='_blank'>华为新品全面上线，更多优惠猛戳》》</a>"},{"id":172,"skus":"[{\"images\":\"http://image.leyou.com/images/4/4/1524297665925.jpg\",\"price\":81800,\"id\":11154856647,\"title\":\"华为（HUAWEI） 华为 畅享6S 手机 金色 公开全网通(3G+32G)\"},{\"images\":\"http://image.leyou.com/images/12/5/1524297666863.jpg\",\"price\":79800,\"id\":11282353344,\"title\":\"华为（HUAWEI） 华为 畅享6S 手机 银色 公开全网通(3G+32G)\"},{\"images\":\"http://image.leyou.com/images/10/3/1524297666454.jpg\",\"price\":84900,\"id\":11653636876,\"title\":\"华为（HUAWEI） 华为 畅享6S 手机 粉色 公开全网通(3G+32G)\"}]","subTitle":"京东配送！  骁龙芯片！金属机身！  <a href=\"https://item.jd.com/21669543700.html\" target=\"_blank\">【新品畅享7s】</a>"},{"id":171,"skus":"[{\"images\":\"http://image.leyou.com/images/3/0/1524297663526.jpg\",\"price\":548800,\"id\":11319391377,\"title\":\"华为（HUAWEI） 华为P20 Pro 全面屏 手机 亮黑色 全网通 6GB+128GB\"},{\"images\":\"http://image.leyou.com/images/11/1/1524297664464.jpg\",\"price\":498800,\"id\":26652898174,\"title\":\"华为（HUAWEI） 华为P20 Pro 全面屏 手机 宝石蓝 全网通 6GB+64GB\"},{\"images\":\"http://image.leyou.com/images/9/11/1524297664033.jpg\",\"price\":538800,\"id\":26652898177,\"title\":\"华为（HUAWEI） 华为P20 Pro 全面屏 手机 极光色 全网通 6GB+64GB\"},{\"images\":\"http://image.leyou.com/images/3/14/1524297664846.jpg\",\"price\":498800,\"id\":26652898180,\"title\":\"华为（HUAWEI） 华为P20 Pro 全面屏 手机 樱粉金 全网通 6GB+64GB\"}]","subTitle":"【全国多仓发货】送价值158元原装礼盒（自拍杆+数据线+指环扣）+原装耳机！<a href=\"https://item.jd.com/13039618422.html\" target=\"_blank\">抢华为P20</a>"},{"id":153,"skus":"[{\"images\":\"http://image.leyou.com/images/13/1/1524297624866.jpg\",\"price\":132800,\"id\":10522143816,\"title\":\"华为（HUAWEI） 华为 麦芒5 手机 香槟金 全网通(4G+64G)标配\"},{\"images\":\"http://image.leyou.com/images/10/3/1524297625644.jpg\",\"price\":149900,\"id\":10710971191,\"title\":\"华为（HUAWEI） 华为 麦芒5 手机 玫瑰金 全网通(4G+64G)标配\"},{\"images\":\"http://image.leyou.com/images/12/13/1524297625338.jpg\",\"price\":149900,\"id\":12153562122,\"title\":\"华为（HUAWEI） 华为 麦芒5 手机 苍穹灰 全网通(4G+64G)标配\"}]","subTitle":"【现货速发】5.5英寸大屏、八核处理器！ <a href=\"https://item.jd.com/16986927363.html\" target=\"_blank\">【新品麦芒6】</a>"},{"id":144,"skus":"[{\"images\":\"http://image.leyou.com/images/1/7/1524297606671.jpg\",\"price\":81800,\"id\":24748737911,\"title\":\"华为（HUAWEI） 华为 畅享6S 手机 银色 公开全网通(3G+32G)\"},{\"images\":\"http://image.leyou.com/images/11/0/1524297606082.jpg\",\"price\":81800,\"id\":24748737913,\"title\":\"华为（HUAWEI） 华为 畅享6S 手机 金色 公开全网通(3G+32G)\"},{\"images\":\"http://image.leyou.com/images/11/6/1524297607083.jpg\",\"price\":82900,\"id\":24748737915,\"title\":\"华为（HUAWEI） 华为 畅享6S 手机 粉色 公开全网通(3G+32G)\"}]","subTitle":"指纹识别！金属机身！3+32大内存骁龙八核长续航！<a href=\"https://item.jd.com/16097496669.html\" target=\"_blank\">中兴A3特惠促销，下单有礼</a>"},{"id":132,"skus":"[{\"images\":\"http://image.leyou.com/images/10/3/1524297582183.jpg\",\"price\":119800,\"id\":24441650455,\"title\":\"华为（HUAWEI） 华为nova青春版 手机 魅海蓝 (4G+64G)移动全网通\"},{\"images\":\"http://image.leyou.com/images/7/3/1524297583192.jpg\",\"price\":119900,\"id\":24441650457,\"title\":\"华为（HUAWEI） 华为nova青春版 手机 铂光金 (4G+64G)移动全网通\"},{\"images\":\"http://image.leyou.com/images/14/9/1524297582770.jpg\",\"price\":119900,\"id\":24441650458,\"title\":\"华为（HUAWEI） 华为nova青春版 手机 幻夜黑 (4G+64G)移动全网通\"},{\"images\":\"http://image.leyou.com/images/1/8/1524297583499.jpg\",\"price\":139900,\"id\":26222067490,\"title\":\"华为（HUAWEI） 华为nova青春版 手机 珍珠白 (4G+64G)标准版\"}]","subTitle":"【现货速发，京东配送】麒麟658！柔光护眼屏！双面弧面玻璃！<a href=\"https://item.jd.com/26510592706.html\" target=\"_blank\">华为P20震撼上市！</a>"},{"id":97,"skus":"[{\"images\":\"http://image.leyou.com/images/8/15/1524297508547.jpg\",\"price\":81900,\"id\":14236495927,\"title\":\"华为（HUAWEI） 华为 畅享6s 4G手机 银色 全网通( 3G RAM+32G ROM)标配\"},{\"images\":\"http://image.leyou.com/images/15/0/1524297509044.jpg\",\"price\":83800,\"id\":14236495928,\"title\":\"华为（HUAWEI） 华为 畅享6s 4G手机 粉色 全网通( 3G RAM+32G ROM)标配\"},{\"images\":\"http://image.leyou.com/images/12/13/1524297507968.jpg\",\"price\":81800,\"id\":14236495929,\"title\":\"华为（HUAWEI） 华为 畅享6s 4G手机 金色 全网通( 3G RAM+32G ROM)标配\"}]","subTitle":"指纹识别！金属机身！3+32大内存骁龙八核长续航！<a href=\"https://item.jd.com/21870224382.html\" target=\"_blank\">【华为新品抢先购→华为畅享8】</a>"},{"id":95,"skus":"[{\"images\":\"http://image.leyou.com/images/3/12/1524297502508.jpg\",\"price\":279900,\"id\":21678745116,\"title\":\"华为（HUAWEI） 华为nova2S 全面屏手机 浅艾蓝 全网通(6G+64G)\"},{\"images\":\"http://image.leyou.com/images/9/9/1524297503422.jpg\",\"price\":279900,\"id\":21678745118,\"title\":\"华为（HUAWEI） 华为nova2S 全面屏手机 樱粉金 全网通(6G+64G)\"},{\"images\":\"http://image.leyou.com/images/10/15/1524297503896.jpg\",\"price\":259900,\"id\":21678745119,\"title\":\"华为（HUAWEI） 华为nova2S 全面屏手机 相思红 全网通(4G+64G )\"},{\"images\":\"http://image.leyou.com/images/7/9/1524297503024.jpg\",\"price\":279900,\"id\":21678745122,\"title\":\"华为（HUAWEI） 华为nova2S 全面屏手机 银钻灰 全网通(6G+64G)\"},{\"images\":\"http://image.leyou.com/images/4/8/1524297501959.jpg\",\"price\":279900,\"id\":21678745124,\"title\":\"华为（HUAWEI） 华为nova2S 全面屏手机 曜石黑 全网通(6G+64G)\"}]","subTitle":"送乐心运动手环+品胜10000毫安电源+暴风VR眼镜+usb分线器！<a href=\"https://item.jd.com/26399946248.html\" target=\"_blank\">华为nova3e</a>"},{"id":91,"skus":"[{\"images\":\"http://image.leyou.com/images/2/6/1524297490220.jpg\",\"price\":248800,\"id\":12260682497,\"title\":\"华为（HUAWEI） 华为 P10 全网通4G智能手机 钻雕金（4G+64G）\"},{\"images\":\"http://image.leyou.com/images/4/6/1524297491674.jpg\",\"price\":278800,\"id\":12318888928,\"title\":\"华为（HUAWEI） 华为 P10 全网通4G智能手机 玫瑰金（4G+64G）\"},{\"images\":\"http://image.leyou.com/images/8/8/1524297490754.jpg\",\"price\":268800,\"id\":12320370716,\"title\":\"华为（HUAWEI） 华为 P10 全网通4G智能手机 曜石黑（4G+64G）\"},{\"images\":\"http://image.leyou.com/images/14/1/1524297492581.jpg\",\"price\":268800,\"id\":12320370717,\"title\":\"华为（HUAWEI） 华为 P10 全网通4G智能手机 陶瓷白（4G+64G）\"},{\"images\":\"http://image.leyou.com/images/9/9/1524297492180.jpg\",\"price\":248800,\"id\":12320370718,\"title\":\"华为（HUAWEI） 华为 P10 全网通4G智能手机 草木绿（4G+64G）\"},{\"images\":\"http://image.leyou.com/images/0/10/1524297491296.jpg\",\"price\":248800,\"id\":12320370719,\"title\":\"华为（HUAWEI） 华为 P10 全网通4G智能手机 钻雕蓝（4G+64G）\"}]","subTitle":"货票同行~支持七天保价，隔日达！<a href=\"https://item.jd.com/27179904421.html\" target=\"_blank\">预约抢购华为P20</a>"},{"id":78,"skus":"[{\"images\":\"http://image.leyou.com/images/15/9/1524297461177.jpg\",\"price\":229900,\"id\":26509792441,\"title\":\"华为（HUAWEI） 华为 nova 3E 全面屏手机 樱语粉 移动全网通（4G+128G）\"},{\"images\":\"http://image.leyou.com/images/4/8/1524297461644.jpg\",\"price\":219900,\"id\":26509792443,\"title\":\"华为（HUAWEI） 华为 nova 3E 全面屏手机 铂光金 移动全网通（4G+128G）\"},{\"images\":\"http://image.leyou.com/images/3/10/1524297460763.jpg\",\"price\":219900,\"id\":26509792445,\"title\":\"华为（HUAWEI） 华为 nova 3E 全面屏手机 克莱因蓝 移动全网通（4G+128G）\"},{\"images\":\"http://image.leyou.com/images/15/9/1524297460088.jpg\",\"price\":219900,\"id\":26509792447,\"title\":\"华为（HUAWEI） 华为 nova 3E 全面屏手机 幻夜黑 移动全网通（4G+128G）\"}]","subTitle":"现货速发！前置2400万，后置1600万双摄！自带原装耳机保护套。新品<a href=\"https://item.jd.com/26881279032.html\" target=\"_blank\">P20pro</a>极光色"},{"id":175,"skus":"[{\"images\":\"http://image.leyou.com/images/7/3/1524297671280.jpg\",\"price\":219900,\"id\":26400483774,\"title\":\"华为（HUAWEI） nova 3e 手机 幻夜黑 全网通（4G+128G）\"},{\"images\":\"http://image.leyou.com/images/7/4/1524297671725.jpg\",\"price\":219900,\"id\":26400483776,\"title\":\"华为（HUAWEI） nova 3e 手机 克莱因蓝 全网通（4G+128G）\"},{\"images\":\"http://image.leyou.com/images/6/11/1524297672093.jpg\",\"price\":219900,\"id\":26400483780,\"title\":\"华为（HUAWEI） nova 3e 手机 樱语粉 全网通（4G+128G）\"},{\"images\":\"http://image.leyou.com/images/14/11/1524297672497.jpg\",\"price\":219900,\"id\":26804041942,\"title\":\"华为（HUAWEI） nova 3e 手机 铂光金 移动全网通（4G+128G）\"}]","subTitle":"【现货，送五重好礼】前置2400万自然美妆，送华为原装耳机等！<a href=\"https://item.jd.com/21698630782.html\" target=\"_blank\">华为nova2s热销中~</a>"}]
        List<Goods> goodsList = result.getContent();
        //解析聚合结果
        Aggregations aggs = result.getAggregations();
        // [{"id":76,"isParent":false,"name":"手机","parentId":75,"sort":1}]
        List<Category> categories = parseCategoryAgg(aggs.get(categoryAggName));
        // [{"id":2032,"image":"http://img10.360buyimg.com/popshop/jfs/t2119/133/2264148064/4303/b8ab3755/56b2f385N8e4eb051.jpg","letter":"O","name":"OPPO"},{"id":8557,"image":"http://img10.360buyimg.com/popshop/jfs/t5662/36/8888655583/7806/1c629c01/598033b4Nd6055897.jpg","letter":"H","name":"华为（HUAWEI）"},{"id":12669,"image":"http://img13.360buyimg.com/popshop/jfs/t3511/131/31887105/4943/48f83fa9/57fdf4b8N6e95624d.jpg","letter":"M","name":"魅族（MEIZU）"},{"id":15127,"image":"http://img14.360buyimg.com/popshop/jfs/t2701/34/484677369/7439/ee13e8fa/5716e2c4Nc925baf3.jpg","letter":"S","name":"三星（SAMSUNG）"},{"id":18374,"image":"http://img10.360buyimg.com/popshop/jfs/t7084/169/439244907/4647/724c7958/598042c9N6e4e79e5.jpg","letter":"X","name":"小米（MI）"},{"id":25591,"image":"http://img13.360buyimg.com/popshop/jfs/t2458/318/1092287831/5774/b7b4ff89/563b3484N9ba68e13.jpg","letter":"V","name":"vivo"},{"id":27094,"image":"http://img14.360buyimg.com/popshop/jfs/t2101/155/882410684/3730/b24b14db/5631cd12N7548352d.jpg","letter":"N","name":"努比亚（nubia）"},{"id":27306,"image":"http://img10.360buyimg.com/popshop/jfs/t5182/149/2437584670/15334/2e1ebf3/591aa1abN602ebecf.jpg","letter":"S","name":"360"},{"id":38126,"image":"http://img14.360buyimg.com/popshop/jfs/t3553/225/1930378991/5787/c2ebdd72/5836e479N88a98abb.jpg","letter":"M","name":"美图（meitu）"},{"id":91515,"image":"http://img13.360buyimg.com/popshop/jfs/t1954/102/907711365/5487/9f26868f/5631ccdeNe8df5efb.jpg","letter":"C","name":"锤子（smartisan）"}]
        List<Brand> brands = parseBrandAgg(aggs.get(brandAggName));
        //完成规格参数聚合
        List<Map<String, Object>> specs = null;
        if (categories != null && categories.size() == 1) {
            //商品分类存在并且数量为1,可以聚合规格参数
            specs = buildSpecificationAgg(categories.get(0).getId(), basicQuery);
        }

        return new SearchResult(total, totalPage, goodsList, categories, brands, specs);
    }

    private List<Map<String, Object>> buildSpecificationAgg(Long cid, QueryBuilder basicQuery) {
        List<Map<String, Object>> specs = new ArrayList<>();
        // 1.查询需要聚合的规格参数
        List<SpecParam> params = specClient.queryParamList(null, cid, true);
        // 2.聚合
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 2.1要带上查询条件
        queryBuilder.withQuery(basicQuery);
        // 2.2聚合
        for (SpecParam param : params) {
            String name = getKey(param);
            queryBuilder.addAggregation(AggregationBuilders.terms(name).field("specs." + name + ".keyword"));
        }
        // 3.获取结果
        AggregatedPage<Goods> result = template.queryForPage(queryBuilder.build(), Goods.class);
        // 4.解析结果
        Aggregations aggs = result.getAggregations();
        for (SpecParam param : params) {
            String name = getKey(param);
            StringTerms terms = aggs.get(name);
            List<String> options = terms.getBuckets().stream().map(StringTerms.Bucket::getKeyAsString).collect(Collectors.toList());
            //准备map
            Map<String, Object> map = new HashMap<>();
            map.put("k", param.getName());
            map.put("options", options);
            specs.add(map);
        }
        return specs;
    }

    private String getKey(SpecParam specParam) {
        if (NewVersion) {
            Long id = specParam.getId();
            return "id_" + id;
        }
        return specParam.getName();
    }

    private List<Brand> parseBrandAgg(LongTerms terms) {
        try {
            List<Long> ids = terms.getBuckets().stream().map(b -> b.getKeyAsNumber().longValue()).collect(Collectors.toList());
            return brandClient.queryBrandByIds(ids);
        } catch (Exception e) {
            return null;
        }
    }

    private List<Category> parseCategoryAgg(LongTerms terms) {
        try {
            List<Long> ids = terms.getBuckets().stream().map(b -> b.getKeyAsNumber().longValue()).collect(Collectors.toList());
            return categoryClient.queryCategoryByIds(ids);
        } catch (Exception e) {
            return null;
        }
    }
}
